<template>
	<view class="chat-container relative">
		<!-- 消息列表 -->
		<scroll-view scroll-y class="message-list" :scroll-top="scrollTop" id="scr">
			<block v-if="messages.length">
				<view v-for="(msg, idx) in messages" :key="idx" :class="['message',msg.sender == openid ? 'self' :'other']"
					:style="{justifyContent: msg.sender == openid ? 'flex-end' : 'flex-start'}">
					<view v-if="msg.sender !== openid" class="avatar">
						<image :src="msg.avater"></image>
					</view>
					<view class="message-content">
						<view class="sub-title-text">
							{{msg.date}}
						</view>
						<view v-if="msg.text" class="text">{{ msg.text }}</view>
						<view v-if="msg.image" class="image" style="min-width: 490rpx; max-width: 600rpx;"
							@click="preImg(msg.image)">
							<image :src="msg.image" mode="widthFix"></image>
							<!-- <image src="../../static/logo.png" mode=""></image> -->
						</view>
					</view>
					<view v-if="msg.sender == openid" class="avatar">
						<!-- {{msg.avater}} -->
						<image :src="msg.avater"></image>
						<!-- <image src="../../static/logo.png" mode=""></image> -->
					</view>
				</view>
			</block>
		</scroll-view>
		<view class="send-box absolute">
			<input type="text" v-model="newMessage" placeholder="输入消息" />
			<button @click="uploadImage">上传图片</button>
			<!-- <button @click="getImage">获取图片</button> -->

			<button @click="sendMessage" style="background-color: #42b983;margin-left: 10rpx;">发送</button>
		</view>
	</view>

</template>

<script>
	export default {
		data() {
			return {
				messages: [
					// {
					// 	text: '你好！',
					// 	type: 'other',
					// 	avatar: 'http://example.com/avatar1.jpg',
					// 	date: '2024-01-07 17:59:21'
					// },
					// {
					// 	image: '../../static/logo.png',
					// 	type: 'self',
					// 	avatar: 'http://example.com/avatar2.jpg',
					// 	date: '2024-01-07 17:59:21'
					// },
					// {
					// 	text: '我也在学，我们可以一起交流！',
					// 	type: 'other',
					// 	avatar: 'http://example.com/avatar1.jpg',
					// 	date: '2024-01-07 17:59:21'
					// }
				],
				newMessage: '',
				uploadedImage: '',
				scrollTop: 0,
				openid: "",
				sessionid: "",
				timer: null,
			};
		},
		onLoad(prop) {
			// console.log(prop,this.getSessionDetail(prop.id))
			// getSessionDetail
			// this.postMsg(prop.id)
			this.sessionid = prop.id // 会话id
			// this.sessionid = "f380561066aaf2ca05156e5869112ed5" // 会话id
			this.openid = uni.getStorageSync("openid")
			// this.getSessionDetail("f380561066aaf2ca05156e5869112ed5")
			this.getSessionDetail(this.sessionid)
			this.timer = setInterval(() => this.getSessionDetail(this.sessionid), 4500)
			// this.getImage(
			// 	'cloud://animal-4g5ks6ct0e7f251e.616e-animal-4g5ks6ct0e7f251e-1315698572/avater/tmp_8b9b1dc1b9ea3f1d9c9fd0542f9c82f6e992b30c96affe33.jpg'
			// 	)
		},
		methods: {
			uploadImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						this.uploadedImage = res.tempFilePaths[0];
						let fileName = this.uploadedImage.split('/')[this.uploadedImage.split('/').length - 1]
						let resAvater = await this.$clould.uploadFile({
							cloudPath: 'avater/' + fileName,
							filePath: this.uploadedImage
						})
						this.sendMessage({
							image: this.uploadedImage
						});
						this.updateScrollTarget();
					}
				});
			},
			sendMessage(msg) {
				let text = this.newMessage
				let image = msg.image
				if (text.trim()) {
					this.postMsg(this.sessionid, '', text)
					this.newMessage = '';
					this.updateScrollTarget();
				}
				if (image) {
					uni.showLoading({
						mask: true,
						title: "上传中"
					})
					let fileName = image.split('/').pop();
					this.$clould.uploadFile({
						cloudPath: 'bolost/' + fileName,
						filePath: image,
						success: res => {
							uni.hideLoading()
							this.postMsg(this.sessionid, res.fileID, '')
							// resolve(res.fileID);
						},
						fail: err => {
							uni.hideLoading()
							uni.showToast({
								title: '请上传图片',
								icon: 'error',
								duration: 2000
							})
							// reject(err);
						}
					});
					this.uploadedImage = '';
					this.updateScrollTarget();
				}
			},
			// 向下滚动
			updateScrollTarget() {
				// 获取最新消息的DOM元素，并设置ID
				this.scrollTop += 550
				uni.pageScrollTo({
					scrollTop: this.scrollTop,
					selector: 'scr',
				})
			},
			// 进入聊天页面、获取最新消息
			async getSessionDetail(id) {
				let res = await wx.cloud.callFunction({
					name: 'logins',
					data: {
						useName: 'getSessionDetail',
						id
					}
				})
				console.log("res:", res.result)
				this.messages = res.result ? res.result.content : []
				this.updateScrollTarget();
				return res
			},
			// 发送消息
			async postMsg(id, image, text) {
				let res = await wx.cloud.callFunction({
					name: "logins",
					data: {
						useName: "sendMsg",
						id,
						content: {
							avater: uni.getStorageSync('userinfo').avater,
							date: this.$formatDateTime(new Date(), true),
							image: image || "", // 聊天图片
							text: text || "" // 内容
						}
					}
				})
				this.getSessionDetail(this.sessionid)
				// console.log("resMsg:", res)
			},
			// 下载上传的文件
			getImage(img) {
				this.$clould.downloadFile({
					fileID: img,
					success: (res) => {
						console.log(res.tempFilePath)
						return res.tempFilePath
					},
					fail: (err) => {
						console.log("err:", err)
					}
				})
			},
			preImg(img) {
				uni.previewImage({
					urls: [img],
				})
			}
		},
		onUnload() {
			clearInterval(this.timer)
			this.timer = null
		}
	};
</script>

<style lang="scss" scoped>
	.chat-container {
		display: flex;
		flex-direction: column;
		height: 100vh;

		.message-list {
			flex-grow: 1;
			overflow-y: auto;
			padding: 20rpx;
			height: calc(80vh-100rpx);
			margin-bottom: 120rpx;

			.message {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;

				&.self {
					.avatar {
						order: 1;
						margin: 0 20rpx;
					}

					.message-content {
						background-color: #dcf8c6;
						border-radius: 10rpx 0 10rpx 10rpx;
						padding: 20rpx;
					}
				}

				&.other {
					.avatar {
						margin-right: 20rpx;
					}

					.message-content {
						background-color: #e9e9eb;
						border-radius: 0 10rpx 10rpx 10rpx;
						padding: 20rpx;
					}
				}

				.avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;

					image {
						width: 100%;
						height: 100%;
						object-fit: cover;
					}
				}

				.text {
					word-wrap: break-word;
					white-space: pre-wrap;
				}

				.image {
					margin-top: 10rpx;
					width: 100%;
					max-width: 300rpx;
					height: auto;

					image {
						width: 100%;
						max-height: 380rpx;
						height: auto;
						object-fit: contain;
					}
				}
			}
		}

		.send-box {
			display: flex;
			align-items: center;
			// padding: 20rpx;
			width: 100%;
			margin-bottom: 20rpx;
			box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
			bottom: 0;
			z-index: 20;
			background-color: #FFF;
			height: 100rpx;

			input {
				flex-grow: 1;
				border: none;
				border-radius: 10rpx;
				margin-right: 20rpx;
			}

			button {
				border: none;
				border-radius: 10rpx;
				background-color: #007AFF;
				color: white;
			}
		}
	}
</style>